#ifndef _APP_H_
#define _APP_H_

#include <string>
#include <mutex>
#include <list>
#include <memory>

#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <freertos/task.h>
#include <esp_timer.h>

#include "esp_task_manager.h"

#include "ws2812.h"
#define SCHEDULE_EVENT (1 << 0)

enum DeviceState {
  kDeviceStateUnknown,          // 0 - 未知状态
  kDeviceStateStarting,         // 1 - 应用启动中
  kDeviceStateHardwareInit,     // 2 - 硬件初始化中
  kDeviceStateHardwareError,    // 3 - 硬件初始化错误
  kDeviceStateHardwareOk,       // 4 - 硬件初始化完成
  kDeviceStateConnecting,       // 5 - 连接中
  kDeviceStateWifiConfig,       // 6 - WiFi配网中
  kDeviceStateNetworkError,     // 7 - 网络错误
  kDeviceStateNetworkOk,        // 8 - 网络连接成功
  kDeviceStateMqttConnecting,   // 9 - MQTT连接中
  kDeviceStateMqttError,        // 10 - MQTT连接错误
  kDeviceStateMqttOk,           // 11 - MQTT连接成功
  kDeviceStateOta,              // 12 - OTA更新中
  kDeviceStateOtaWrite,         // 13 - OTA写入
  kDeviceStateOtaError,         // 14 - OTA更新错误
  kDeviceStateIdle,             // 15 - 正常工作状态
  kDeviceStateError,            // 16 - 错误状态
};

class App {
public:
    static App& GetInstance() {
        static App instance;
        return instance;
    }
    // 删除拷贝构造函数和赋值运算符
    App(const App&) = delete;
    App& operator=(const App&) = delete;
    // 错误状态标志位
    enum ErrorFlags : uint16_t {
        ERROR_NONE          = 0x0000,  // 无错误
        ERROR_HARDWARE      = 0x0001,  // 硬件错误
        ERROR_WIFI          = 0x0002,  // WiFi连接错误
        ERROR_MQTT          = 0x0004,  // MQTT连接错误
        ERROR_OTA           = 0x0008,  // OTA更新错误
    };
    // 主任务执行器
    std::shared_ptr<TaskExecutor> main_task_executor_;
    // LED任务执行器
    std::shared_ptr<TaskExecutor> led_task_executor_;

    // 获取错误状态
    uint16_t GetErrorFlags() const { return error_flags_; }
    bool HasError() const { return error_flags_ != ERROR_NONE; }
    bool HasError(ErrorFlags flag) const { return (error_flags_ & flag) != 0; }
    
    // 设置和清除错误标志
    void SetError(ErrorFlags flag);
    void ClearError(ErrorFlags flag);
    void ClearAllErrors();


    void Start();
    void SetDeviceState(DeviceState state);
    void SetDeviceStateInternal(DeviceState state);
    DeviceState GetDeviceState() const { return device_state_; }
    
private:
    App();
    ~App();

    // 事件组句柄
    EventGroupHandle_t event_group_ = nullptr;
    volatile uint16_t error_flags_ = ERROR_NONE;  // 错误状态标志位
    volatile DeviceState device_state_ = kDeviceStateUnknown;
    volatile DeviceState last_device_state_ = kDeviceStateUnknown;
    volatile bool is_initialization_complete_ = false;  // 初始化完成标志

    void ShowDeviceStateOnLed();
    void CheckAndSetFinalState();  // 检查并设置最终状态（error/idle）

};

#endif